/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.myapp.wicket;

import dto.User;
import org.apache.wicket.Request;
import org.apache.wicket.protocol.http.WebSession;

import repository.UserRepository;

public final class SignInSession extends WebSession
{
    /** Trivial user representation */
    private int userId;
    private String user;
    private String role;

    /**
     * Constructor
     * 
     * @param request
     */
    protected SignInSession(Request request)
    {
        super(request);
    }

    /**
     * Checks the given username and password, returning a User object if if the username and
     * password identify a valid user.
     * 
     * @param username
     *            The username
     * @param password
     *            The password
     * @return True if the user was authenticated
     */
    public final boolean authenticate(final String username, final String password)
    {
        if (user == null)
        {
            UserRepository userRepository = new UserRepository();
            User gotUser =new User();
            gotUser=userRepository.getByLogin(username);
            // Trivial password "db"
            if (gotUser != null && gotUser.password.equalsIgnoreCase(password))
            {
                userId = gotUser.id;
                user = username;
                role = gotUser.role;
            }
        }

        return user != null;
    }

    /**
     * @return True if user is signed in
     */
    public boolean isSignedIn()
    {
        return user != null;
    }

    public int getUserId()
    {
        return userId;
    }
    
    /**
     * @return User
     */
    public String getUser()
    {
        return user;
    }

    /**
     * @param user
     *            New user
     */
    public void setUser(final String user)
    {
        this.user = user;
    }
    
    public String getRole()
    {
        return role;
    }
}